package com.project.config;

import com.project.Main2;
import com.project.util.LocalDateChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;

@Configuration
@ComponentScan(basePackageClasses = Main2.class)
@EnableWebMvc
public class MVCConfig implements WebMvcConfigurer {
    @Autowired
    private RequestMappingHandlerAdapter adapter;


    @PostConstruct
    public void addConversionConfig() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter
                .getWebBindingInitializer();
        if (initializer.getConversionService() != null) {
            GenericConversionService converService = (GenericConversionService) initializer.getConversionService();
            converService.addConverter(new LocalDateChange());
        }
    }
    //设置编码集
    @Override
    public void extendMessageConverters(
            List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter stringHttpMessageConverter =
                (StringHttpMessageConverter) converters.get(1);
        stringHttpMessageConverter.setDefaultCharset(
                Charset.forName("utf-8"));
    }

    //设置静态页面访问路径
    @Override
    public void addResourceHandlers(
            ResourceHandlerRegistry registry) {
        //客户端以/html/的请求，访问resources/static/html/相关的页面
        registry.addResourceHandler("/html/**").
                addResourceLocations("classpath:/static/html/");
    }

}
